package com.ropeok.service.serviceimpl;


import com.ropeok.Exception.ServiceException;
import com.ropeok.Result.Result;
import com.ropeok.Utils.JwtUtils;
import com.ropeok.Utils.MD5;
import com.ropeok.Utils.RedisUtil;
import com.ropeok.constant.ResultConstant;
import com.ropeok.dto.UserDto;
import com.ropeok.mapper.UserDtoMapper;
import com.ropeok.service.UserLoginService;
import com.ropeok.dto.UserLoginDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private UserDtoMapper userDtoMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * admin：password（admin123），zhangsan：password（zhangsan123）
     * @param userLoginDtoDto 表单中的user
     * @return 用户信息
     */
    @Override
    public UserDto login(UserLoginDto userLoginDtoDto) {
//        admin：password为（admin123），zhangsan：password为（zhangsan123）
        String loginName=userLoginDtoDto.getUsername();
        String loginPassword=userLoginDtoDto.getPassword();
        UserDto user = userDtoMapper.QueryUserInfo(loginName);
        if (user != null) {
            if (MD5.MD5Encrypt(loginPassword,user.getSalt()).equals(user.getPassword())){
                System.out.println(user);
                return user;
            }else {
                throw new ServiceException(ResultConstant.DATA_NOT_EXIST,"密码错误");
            }
        }else {
            throw new ServiceException(ResultConstant.DATA_NOT_EXIST,"用户名错误");
        }
    }

    /**
     * 得到token
     * @param user
     * @return
     */
    public String CreateToken(UserDto user){
        Map<String, String> payload = new HashMap<>();
        payload.put("id", String.valueOf(user.getUserid()));
        payload.put("name", user.getUsername());
        payload.put("expireTime",String.valueOf(user.getExpireTime()));
        String token = JwtUtils.getToken(payload);
        return token;
    }

    /**
     * 判断用户是否有权限访问目前url
     * @param id 该token对应的用户id，在redis存的用户信息当作key
     * @param requestURI 当前访问的uri
     * @return
     */
    @Override
    public Boolean JudgePermission(String id,String requestURI) {
        //在redis中查找存的用户信息
        UserDto user =(UserDto) redisUtil.get(id);
        if (user==null){
            throw new ServiceException(ResultConstant.forbidden,"请重新登录");
        }
        //剩余有效时间小于5分钟,其实可能改成用这个token重新登录就刷新
        if(user.getExpireTime() - System.currentTimeMillis() <= 1000L * 60 * 5) {
                jwtUtils.refreshToken(user);
        }
        //找到该用户所有有权限访问的uri地址
        List<String> uris = user.getUris();
        if (!uris.contains(requestURI)){
            throw new ServiceException(ResultConstant.forbidden,"你没有权限");
        }
        return  true;
    }

}
